#include "communication-device-list.h"

void CommunicationDeviceList::communication(SmartDevicenetProtocol &netProtocol, NetCommunication *netObj)
{
	string command = netProtocol.getCommand();
	if(command != "query")
	{
		return;
	}
	SmartDeviceDatabase *  smartDeviceDatabase = SmartDeviceDatabase::getSmartDeviceDatabase();
	bool                   ok;
	vector<smart_device_t> smartDevices = smartDeviceDatabase->queryDevice(&ok);
	string                 errmsg       = ok ? "" : "error";
	replay(netObj, command, errmsg, smartDevices);
}

void CommunicationDeviceList::replay(NetCommunication *            netObj,
                                     const string &                command,
                                     const string &                errmsg,
                                     const vector<smart_device_t> &smartDeivces)
{
	SmartDevicenetProtocol netProtocol;
	netProtocol.addOperation("list");
	netProtocol.addCommand(command);

	for(auto it = smartDeivces.begin(); it != smartDeivces.end(); it++)
	{
		netProtocol.addListItem(it->operation, it->deviceType, it->deviceNumber);
	}
	netProtocol.addListResult(errmsg);

	string          repalyJsonData = netProtocol.toString();
	vector<uint8_t> packet;
	packet.assign(repalyJsonData.begin(), repalyJsonData.end());
	cout << "------------udp发送----------------" << endl;
	bool ret = netObj->sendPacket(packet);
	if(ret != true)
	{
		fprintf(stderr, "Fail to sendPacket\n");
		return;
	}

	return;
}
